package org.robot.scm.utils;

import java.io.BufferedInputStream;
import java.io.InputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author : Awn create on 2023/12/4 14:54
 */
@Slf4j
public class AudioSoundUtil {

    public static void playSound(InputStream byteStream) {
        try (AudioInputStream audioContent = AudioSystem.getAudioInputStream(new BufferedInputStream(byteStream))) {
            int count;
            byte[] buf = new byte[1024];
            AudioFormat audioFormat = audioContent.getFormat();
            DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat, AudioSystem.NOT_SPECIFIED);
            try (SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo)) {
                sourceDataLine.open(audioFormat);
                sourceDataLine.start();
                while ((count = audioContent.read(buf, 0, buf.length)) != -1) {
                    sourceDataLine.write(buf, 0, count);
                }
                sourceDataLine.drain();
                log.info("audio play sound success");
            }
        } catch (Exception e) {
            log.error("speak audio sound fail", e);
        }
    }
}
